package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.BaseDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateBankCardGetPageDTO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateBankCardVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IOperateBankCardManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * <desc>
 *      运营银联卡管理控制器
 * </desc>
 *
 * @createDate 2018/09/25
 */
@RestController
@RequestMapping("/finance/bankCardManage")
@RefreshScope
public class OperateBankCardManageController extends BaseController{
    @Autowired
    IOperateBankCardManageServiceClient iOperateBankCardManageServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    /**
     * <desc>
     *      审核获取详情
     * <desc/>
     *
     * @param bankCardId
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @ResponseBody
    @RequestMapping(path = "getCardInfo", method = RequestMethod.POST)
    public Object getCheckInfo(String bankCardId){
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankCardId= request.getAttribute("bankCardId")==null?null:request.getAttribute("bankCardId").toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),
                    iOperateBankCardManageServiceClient.getCardInfo(bankCardId));
        }catch (Exception e){
            throw new DataAccessException("【运营-银联卡管理getCardInfo】审核获取详情失败",e);
        }
    }

    /**
     * <desc>
     *      提交审核
     * <desc/>
     *
     * @param bankCardId
     * @param checkStatus
     * @param remark
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.CHECK_BANK_CARD_LOG_DESC)
    @RequestMapping(path = "checkSubmit", method = RequestMethod.POST)
    public Object checkSubmit(String bankCardId,Integer checkStatus,String remark,String token){
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankCardId= request.getAttribute("bankCardId")==null?null:request.getAttribute("bankCardId").toString();
            checkStatus= request.getAttribute("checkStatus")==null?null:Integer.parseInt(request.getAttribute("checkStatus").toString());
            remark= request.getAttribute("remark")==null?"":request.getAttribute("remark").toString();
            token= request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            OperateUserInfoPO userInfo = iOperateUserInfoServiceClient.retrieve(token);
            iOperateBankCardManageServiceClient.checkSubmit(bankCardId,checkStatus,remark,userInfo.getUserId());
            return new MessageVO(bankCardId,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营-银联卡管理checkSubmit】提交审核失败",e);
        }
    }

    /**
     * <desc>
     *      获取分页列表
     * <desc/>
     *
     * @param pageDTO
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @ResponseBody
    @AuthAccessRequired
    @RequestMapping(path = "getPage", method = RequestMethod.POST)
    public Object getPage(OperateBankCardGetPageDTO pageDTO){
        try{
            HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO=HttpProtocolUtil.parseRequestParamToDTO(OperateBankCardGetPageDTO.class,request);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iOperateBankCardManageServiceClient.getPage(pageDTO));
        }catch (Exception e){
            throw new DataAccessException("【运营-银联卡管理getPage】获取分页列表失败",e);
        }
    }

    /**
     * <desc>
     *      导出银行卡信息
     * </desc>
     *
     * @param dto
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/08/30
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("exportBankInfos")
    public Object exportBankInfos(BaseDTO baseDTO,OperateBankCardGetPageDTO dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            baseDTO=HttpProtocolUtil.parseRequestParamToDTO(BaseDTO.class,request);
            dto=HttpProtocolUtil.parseRequestParamToDTO(OperateBankCardGetPageDTO.class,request);
            Page<OperateBankCardVO> vos = iOperateBankCardManageServiceClient.getPage(dto);
            if (vos.getRows() == null || vos.getRows().isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            String[] title = {"项目ID","项目名称","物业名称","开户户名","开户账号","省份","城市","开户银行","默认使用","创建时间","状态","审批人","审批时间","备注"};
            short rowHeight= 420;
            //创建excel工作簿
            HSSFWorkbook workbook=new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet=workbook.createSheet();
            sheet.setDefaultColumnWidth(15);
            //创建第一行
            HSSFRow row=sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell=null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            for (int index = 0; index < vos.getRows().size(); index++) {
                OperateBankCardVO vo = vos.getRows().get(index);
                int rowIndex = index + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(vo.getProjectId());
                noteCell = dataRow.createCell(1);
                noteCell.setCellValue(vo.getProjectName());
                noteCell = dataRow.createCell(2);
                noteCell.setCellValue(vo.getPropertyName());
                noteCell = dataRow.createCell(3);
                noteCell.setCellValue(vo.getUserName());
                noteCell = dataRow.createCell(4);
                noteCell.setCellValue(vo.getBankCardNo());
                noteCell = dataRow.createCell(5);
                noteCell.setCellValue(vo.getProv());
                noteCell = dataRow.createCell(6);
                noteCell.setCellValue(vo.getCity());
                noteCell = dataRow.createCell(7);
                noteCell.setCellValue(vo.getOpenBankName());
                noteCell = dataRow.createCell(8);
                noteCell.setCellValue(vo.getDefaultUse()==1?"是":"否");
                noteCell = dataRow.createCell(9);
                noteCell.setCellValue(vo.getCreateTime());
                noteCell = dataRow.createCell(10);
                noteCell.setCellValue(vo.getCheckStatus() == 1 ? "待审核" :(vo.getCheckStatus() == 2 ? "已审核" : "审核不通过"));
                noteCell = dataRow.createCell(11);
                noteCell.setCellValue(vo.getApprover());
                noteCell = dataRow.createCell(12);
                noteCell.setCellValue(vo.getApproveTime());
                noteCell = dataRow.createCell(13);
                noteCell.setCellValue(vo.getRemark());
            }
            String fileName = String.format("%s_OperateBankInfos_%s.xls",
                    baseDTO.getProjectId(),
                    DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【运营-财务-银联卡管理】导导出银行卡信息失败",e);
        }
    }


    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author Jiaqi.X
     * @createDate 2018/08/17
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.EXPORT_EXCEL_ZHANG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }
}
